﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;

namespace GshopToolCS
{
	/// <summary>
	/// DescriptionPreviewWindow.xaml 的交互逻辑
	/// </summary>
	public partial class DescriptionPreviewWindow : Window
	{
		public DescriptionPreviewWindow()
		{
			InitializeComponent();
		}

		/// <summary>
		/// 设置richText的显示内容
		/// </summary>
		/// <param name="text"></param>
		public void SetText(string text)
		{
			Paragraph paragraph = new Paragraph();
			FindSymbol(text, 0);

			if (indexList.Count <= 0) 
			{
				Run run = new Run(text){
					Text = text,
					Foreground = new SolidColorBrush(Color.FromRgb(255, 255, 255))
				}; 
				paragraph.Inlines.Add(run);
			}
			else
			{
				string text1 = text.Substring(0, indexList.ElementAt(0));
				Run run1 = new Run() {
					Text = text1,
					Foreground = new SolidColorBrush(Color.FromRgb(255, 255, 255))
				};
				paragraph.Inlines.Add(run1);

				for(int i=0;i<indexList.Count;i++)
				{
					int beginIndex = indexList.ElementAt(i);
					string subStr;
					//如果不是最后一个元素
					if (i != indexList.Count - 1) 
					{
						int endIndex = indexList.ElementAt(i + 1);
						subStr = text.Substring(beginIndex, endIndex - beginIndex);
						
					}
					//如果是最后一个元素，则获取方式不一样
					else
					{
						subStr = text.Substring(beginIndex, text.Length - beginIndex);						
					}

					string msgStr = subStr.Substring(7, subStr.Length - 7);
					string colorStr = subStr.Substring(1, 6);
					string rStr = colorStr.Substring(0, 2);
					byte r = Convert.ToByte(rStr, 16);
					byte g = Convert.ToByte(colorStr.Substring(2, 2), 16);
					byte b = Convert.ToByte(colorStr.Substring(4, 2), 16);
					Run run = new Run()
					{
						Text = msgStr,
						Foreground = new SolidColorBrush(Color.FromRgb(r, g, b))
					};
					paragraph.Inlines.Add(run);
				}				
			}

			richBox.Document.Blocks.Add(paragraph);
		}

		/// <summary>
		/// 记录符号'^'一共出现的位置
		/// </summary>
		private List<int> indexList = new List<int>();
		/// <summary>
		/// 递归查找
		/// </summary>
		/// <param name="text"></param>
		/// <param name="beginIndex"></param>
		private void FindSymbol(string text,int beginIndex)
		{
			int index = text.IndexOf('^', beginIndex);
			if (index >= 0) 
			{
				indexList.Add(index);
				FindSymbol(text, index + 1);
			}
		}

	}
}
